package com.dq.repository.order;

import com.dq.domain.orders.UserOrder;
import com.dq.domain.org.Org;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.WxUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author luchangtong
 * @Date 2019/11/27 13:58
 */
@Repository
public interface UserOrderRepository extends JpaRepository<UserOrder,Long> {

    List<UserOrder> findByOrg(Org org);
    /**
     * 根据订单号查询销售单
     * @param orderNo
     * @return
     */
    UserOrder getByOrdersNo(String orderNo);

    /**
     * 根据订单状态和订单来源查询
     * @param status
     * @param sources
     * @return
     */
    Long countByStatusAndOrderSourceIn(UserOrder.UserOrderStatus status, List<UserOrder.OrderSource> sources);

    /**
     * 根据门店和时间分页查询订单
     * @param sysDept
     * @param beginTime
     * @param pageable
     * @return
     */
    Page<UserOrder> findByOrgAndCreateTimeGreaterThanEqual(Org sysDept, Long beginTime, Pageable pageable);

    /**
     * 根据门店和时间统计订单
     * @param sysDept
     * @param beginTime
     * @return
     */
    Long countByOrgAndCreateTimeGreaterThanEqual(Org sysDept, Long beginTime);
    Page<UserOrder> findByOrgAndCreateTimeLessThanEqual(Org sysDept, Long beginTime, Pageable pageable);
    Long countByOrgAndCreateTimeLessThanEqual(Org sysDept, Long beginTime);
    Long countByWxUserAndCreateTimeGreaterThanEqual(WxUser wxUser,Long beginTime);

    Long countByWxUserAndStatusAndDeletedFalse(SysUser wxUser, UserOrder.UserOrderStatus status);

    List<UserOrder> findByOrderSourceAndStatusAndDeletedFalse(UserOrder.OrderSource source, UserOrder.UserOrderStatus status);

    /**
     * 根据用户id查看此用户已核销的总消费金额
     */
    @Query("select COALESCE(sum(price),0) from UserOrder where wxUser = ?1 and status=?2")
    BigDecimal countByWxUser(WxUser wxUser, UserOrder.UserOrderStatus status);

    @Query("select COALESCE(sum(price),0) from UserOrder where wxUser = :wxUser")
    BigDecimal countAllByWxUser(WxUser wxUser);

    @Query("select COALESCE(sum(price),0) from UserOrder where org = ?1 and status=?2 and createTime >=?3 and createTime<=?4")
    BigDecimal countSalePrice(Org org, UserOrder.UserOrderStatus status, Long beginTime, Long endTime);

    List<UserOrder> findByDeletedFalseAndStatusAndIsSettleFalseAndIsOwedFalse(UserOrder.UserOrderStatus status);

}
